<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

include "wechatRequest.php";

define("TOKEN", "imagChina");

class Welcome extends CI_Controller {

    private $request;

    function __construct()
    {
        parent::__construct();
    }

    /**
     * start
     * @return [type] [description]
     */
	public function index()
	{
        //1. $this->valid(); return;//第一次验证成功关闭即可

        //2.
        if (!isset($GLOBALS["HTTP_RAW_POST_DATA"])) {
            exit;
        }

        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];

        if (!empty($postStr)) {

            libxml_disable_entity_loader(true);

            $xml = (array)simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);

            //将数组键名转换为小写
            $this->request = array_change_key_case($xml, CASE_LOWER);

            $wq = new WechatRequest();
            $wq->switchType($this->request);
        }else{

        }
	}

    /**
     * [微信验证]
     * @return [type] [description]
     */
    public function valid()
    {
        $echoStr = $_GET["echostr"];
        // valid signature , option
        if($this->checkSignature()){
            echo $echoStr;
            exit;
        }
    }

    /**
     * 微信验证
     * @return [type] [description]
     */
	private function checkSignature()
	{
        // you must define TOKEN by yourself
        if (!defined("TOKEN")) {
            throw new Exception('TOKEN is not defined!');
        }

        $signature = $this->input->get('signature',true);
        $timestamp = $this->input->get('timestamp',true);
        $nonce = $this->input->get('nonce',true);

		$token = TOKEN;
		$tmpArr = array($token, $timestamp, $nonce);
        // use SORT_STRING rule
		sort($tmpArr, SORT_STRING);
		$tmpStr = implode( $tmpArr );
		$tmpStr = sha1( $tmpStr );

		if( $tmpStr == $signature ){
			return true;
		}else{
			return false;
		}
	}
}
